package main

import (
	"fmt"
	//"github.com/artec/web/controller"
	"github.com/artec/web/info"
	"github.com/artec/web/sdkInit"
	"github.com/artec/web/service"
	"github.com/hyperledger/fabric-sdk-go/pkg/fabsdk"
)

func org1Start(sdk *fabsdk.FabricSDK)  {

	fmt.Println("开始Org1.......")
	//创建Org1通道
	err := sdkInit.CreateChannel(sdk)
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	if !info.Initialized {
		//Org1加入通道
		err = sdkInit.PeerJoinChannel(sdk, info.Org1Name)
		if err != nil {
			fmt.Println(err.Error())
			return
		}
		//安装链码
		err = sdkInit.InstallCC()
		if err != nil {
			fmt.Println(err.Error())
			return
		}
		//实例化链码
		err = sdkInit.InstantiateCC()
		if err != nil {
			fmt.Println(err.Error())
			return
		}
		info.Initialized = !info.Initialized
	}
}

func main() {

	//初始化SDK
	sdk, err := sdkInit.SetupSDK()
	if err != nil {
		fmt.Printf(err.Error())
		return
	}
	defer sdk.Close()

	org1Start(sdk)

	channelClient, err := sdkInit.CreatChannelClient(sdk)
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	//fmt.Println(channelClient)
	info.Client = channelClient

	msg, err := service.Query("A")
	if err != nil {
		msg = "没有查询到对应的信息"
		fmt.Println(msg)
	} else {
		fmt.Println("A 资产为：" + msg)
	}

	msg, err = service.Transfer("A", "B", "10")
	if err != nil {
		msg = err.Error()
		fmt.Println(msg)
	} else {
		fmt.Println("交易成功，tx: " + msg)
	}

	msg, err = service.Query("A")
	if err != nil {
		msg = "没有查询到对应的信息"
		fmt.Println(msg)
	} else {
		fmt.Println("A 资产为：" + msg)
	}

	msg, err = service.Register("C", "300")
	if err != nil {
		msg = err.Error()
		fmt.Println(msg)
	} else {
		fmt.Println("注册成功，tx: " + msg)
	}

	msg, err = service.Delete("A")
	if err != nil {
		msg = err.Error()
		fmt.Println(msg)
	} else {
		fmt.Println("注销成功，tx: " + msg)
	}
}
